package art.server.servlets;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import art.server.db.DatabaseHandler;
import art.server.db.entities.Art;
import art.server.db.entities.PortalUser;

public class ArtUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator iter = upload.getItemIterator(request);
			Art art = new Art();
			art.setUploadedOn(new Date());
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				InputStream stream = item.openStream();
				if (item.isFormField()) {
					// Normal field;
					String value = Streams.asString(stream);
					if (name.equals("titleField")) {
						art.setTitle(value);
					} else if (name.equals("genreField")) {
						art.setGenre(DatabaseHandler.getInstance()
								.getGenreByName(value));
					} else if (name.equals("creatorField")) {
						PortalUser user = DatabaseHandler.getInstance()
								.getUserByEmail(value);
						art.setCreatorId(user.getId());
					} else if (name.equals("artField")) {
						byte[] bytes = value.getBytes();
						if (!value.isEmpty()) {							
							art.setFileName(art.getTitle() + ".txt");
							art.setFile(bytes);
						}
					}
				} else {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					int len;
					byte[] buffer = new byte[8192];
					while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
						out.write(buffer, 0, len);
					}

					int maxFileSize = 10 * (1024 * 1024); // 10 megs max
					if (out.size() > maxFileSize) {
						throw new RuntimeException("File is > than "
								+ maxFileSize);
					}
					art.setFileName(item.getName());
					art.setFile(out.toByteArray());
				}
			}
			DatabaseHandler.getInstance().saveArt(art);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
